package com.example.demo.service;

import cn.hutool.core.date.DateUtil;
import com.example.demo.redis.RedisLockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

/**
 * 模拟库存服务，使用原型模式，获取对象时需要初始化库存数量
 */
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Slf4j
public class StockService {

    /**
     * 原始库存
     */
    private final Integer originalStock;

    /**
     * 当前库存
     */
    private Integer stock;

    public StockService(Integer stock) {
        this.stock = stock;
        this.originalStock = this.stock;
    }

    @Autowired
    private RedisLockService redisLockService;

    /**
     * 打印当前库存状态
     */
    public void printStock() {
        log.info("{} 原始库存{} 当前剩余库存{}", DateUtil.now(), this.originalStock, this.stock);
    }

    /**
     * 普通减库存操作
     * @return
     */
    public boolean subStock() {
        this.stock--;
        return true;
    }

    /**
     * 带锁减库存操作
     * @return
     */
    public boolean subStockWithLock() {
        return redisLockService.runWithLock(this::subStock, "stock", String.valueOf(Thread.currentThread().getId()));
    }

}
